import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/provider/user_info.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/utils/version_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/icon_text_card_widget.dart';
import 'package:xiongan_app_yy/widgets/me_widgets.dart';
import 'package:xiongan_app_yy/widgets/dialog.dart';
import 'package:package_info/package_info.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';

//我的页面
class MePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MePageState();
  }
}

class MePageState extends State<MePage> with AutomaticKeepAliveClientMixin {
  bool mDownload = false;
  String mPath;
  String mTaskId;
  ReceivePort _port = ReceivePort();

  @override
  void initState() {
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      print(progress);
      // 当下载完成时，调用安装
      if (mTaskId == id && status == DownloadTaskStatus.complete) {
        //关闭更新进度框
        //安装下载完的apk
        InstallPlugin.installApk(
            mPath + '/xiongan.apk', 'com.example.xiongan_app_yy')
            .then((result) {
          setState(() {
            mDownload = false;
          });
          print('install apk $result');
        }).catchError((error) {
          setState(() {
            mDownload = false;
          });
          print('install apk error: $error');
        });
      }
    });
    FlutterDownloader.registerCallback(downloadCallback);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: new AppBar(
        backgroundColor: Color(0XFF00A5F1),
        automaticallyImplyLeading: false,
        //设置没有返回按钮
        title: Text(
          "我的",
          style: TextStyle(fontSize: 18),
        ),
        elevation: 0,
        centerTitle: true,
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            HImgBoxWidget(
                phone: Provider
                    .of<UserInfo>(context)
                    .phone,
                imgSrc: Provider
                    .of<UserInfo>(context)
                    .imgSrc ?? "",
                boxBg: Color(0XFF00A5F1)),
            Expanded(
              child: Scrollbar(
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        IconTextCardWidget(
                          title: "个人资料",
                          iconImage: "assets/images/personal.png",
                          margin: EdgeInsets.only(top: 10),
                          onPressed: () {
                            Navigator.pushNamed(context, "/personal_data_page",
                                arguments: {
                                  "id": DataSingleton().Data.id,
                                  "other": false
                                });
                          },
                        ),
                        IconTextCardWidget(
                          title: "修改密码",
                          iconImage: "assets/images/password.png",
                          onPressed: () {
                            Navigator.pushNamed(context,
                                "/change_password_page");
                          },
                        ),
                        IconTextCardWidget(
                          title: "二维码名片",
                          iconImage: "assets/images/business_card.png",
                          onPressed: () {
                            Navigator.pushNamed(context, "/card_qr_codePage");
                          },
                        ),
                        IconTextCardWidget(
                          title: "通讯录",
                          iconImage: "assets/images/book.png",
                          border: Border.fromBorderSide(BorderSide.none),
                          onPressed: () {
                            Navigator.pushNamed(context, "/addressBook");
                          },
                        ),
                        IconTextCardWidget(
                          title: "功能介绍",
                          iconImage: "assets/images/function.png",
                          margin: EdgeInsets.only(top: 10),
                          onPressed: () {
                            Navigator.pushNamed(
                                context, "/function_introduction_page");
                          },
                        ),
                        IconTextCardWidget(
                          title: "下载二维码",
                          iconImage: "assets/images/download.png",
                          onPressed: () {
                            Navigator.pushNamed(context, "/download_code_page");
                          },
                        ),
                        IconTextCardWidget(
                          title: "检查新版本",
                          iconImage: "assets/images/inspect.png",
                          border: Border.fromBorderSide(BorderSide.none),
                          onPressed: () {
                            _gerData(context);
                          },
                        ),
                        OutBtnWidget(
                          title: "退出登录",
                          color: Colors.black12,
                          callback: () async {
                            Navigator.pop(context);
                          },
                        )
                      ],
                    ),
                  )),
            )
          ],
        ),
      ),
    );
  }

  Future<String> getNativeVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  void test() {
    TostUtil.showToast("正在开发调试中");
  }

  Future _gerData(BuildContext context) {
    InternetAPI.getInstance().get("WConfiguration/MiVersion/GetLastMiVersion",
            (data) async {
          if (data["currentversion"] != null &&
              VersionUtils.packageInfo.version != data["currentversion"]) {
            String title = '检测到新版本';
            String contenText = '检测到有新版本，是否更新';
            String cancleText = '下次再说';
            String sureText = '立即更新';
            bool dialogChoice = await showDeleteConfirmDialog1(
                context, title, contenText, cancleText, sureText);
            if (dialogChoice == null) {
              print("取消更新");
            } else {
              print("确认更新");
              checkPermission(context);
            }
          } else {
            showDialogContent(context, VersionUtils.packageInfo.version);
          }
        }, errorCallBack: (err) {}, params: {
          'systemtype': 2,
        });
  }

  checkPermission(BuildContext context) async {
    //检查是否已有读写内存权限
    PermissionStatus status = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.storage);
    //判断如果还没拥有读写权限就申请获取权限
    if (status != PermissionStatus.granted) {
      var map = await PermissionHandler()
          .requestPermissions([PermissionGroup.storage]);
      if (map[PermissionGroup.storage] != PermissionStatus.granted) {
        bool dialogChoice = await showDeleteConfirmDialog1(
            context, "权限申请", "需要写入权限下载apk，否则无法更新", "取消", "去设置");
        if (dialogChoice == null) {} else {
          bool isShown = await PermissionHandler()
              .shouldShowRequestPermissionRationale(PermissionGroup.storage);
          if (isShown) {
            checkPermission(context);
          } else {
            bool isOpened = await PermissionHandler().openAppSettings();
          }
        }
      } else {
        //去下载
        print("去下载a");
        if (!mDownload) {
          mDownload = true;
          executeDownload().then((id) {
            setState(() {
              mTaskId = id;
            });
          });
        } else {
          TostUtil.showToast("下载中。。。");
        }
      }
    } else {
      print("去下载b");
      if (!mDownload) {
        mDownload = true;
        executeDownload().then((id) {
          setState(() {
            mTaskId = id;
          });
        });
      } else {
        TostUtil.showToast("下载中。。。");
      }
    }
  }

  /// 下载
  Future<String> executeDownload() async {
    //获取根目录
    String path = await _apkLocalPath;
    setState(() {
      mPath = path;
    });
    //发起请求
    final taskId = await FlutterDownloader.enqueue(
        url: "http://49.235.45.128/wwwroot/cloud/static/app-debug.apk",
        fileName: 'xiongan.apk',
        savedDir: path,
        showNotification: true,
        openFileFromNotification: true);

    return taskId;
  }

  // 获取安装地址
  Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectory();
    return directory.path;
  }

  static void downloadCallback(String id, DownloadTaskStatus status,
      int progress) {
    print(progress);
    print(id);
    print(status.toString());
    final SendPort send =
    IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
